package com.example.samchat;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Timer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

	ArrayList<SamMsg> arData;
	SamMsgAdapter adapter;
	EditText commend;
	String id = "3jo";
	int i = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		arData = new ArrayList<SamMsg>();
		arData.add(new SamMsg("hi", ""));
		arData.add(new SamMsg("", "Hello~"));

		adapter = new SamMsgAdapter(this, 
				R.layout.chatmsg,
				arData);

		ListView list = (ListView)findViewById(R.id.list);
		list.setAdapter(adapter);
		list.setDividerHeight(0);

		DownThread2 thread2 = new DownThread2("http://godling2.cafe24.com/chat/index.php/room/cmsgs/id/31");
		thread2.start();

	}


	class DownThread extends Thread {

		private String mAddr;

		public DownThread(String addr) {
			mAddr = addr;
		}

		public void run() {

			HttpGet get = new HttpGet(mAddr);
			DefaultHttpClient client = new DefaultHttpClient();
			try {
//				Thread.sleep(1000);
				client.execute(get, mResHandler);
			}
			catch (Exception e) {;}
		}
	}

	ResponseHandler<String> mResHandler = new ResponseHandler<String>() {

		@Override
		public String handleResponse(HttpResponse response)
				throws ClientProtocolException, IOException {
			StringBuilder html = new StringBuilder();
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				for (;;) {
					String line = br.readLine();
					if (line == null) break;
					html.append(line + '\n');
				}
				br.close();
				String[] msg=html.toString().split(",");
				Message message = mAfterDown.obtainMessage();
				message.obj = msg[1];
				mAfterDown.sendMessage(message);
			}
			catch (Exception e) {;}
			return null;
		}
	};

	class DownThread2 extends Thread {

		private String mAddr;

		public DownThread2(String addr) {
			mAddr = addr;
		}

		public void run() {
			while (true) {
				HttpGet get = new HttpGet(mAddr);
				DefaultHttpClient client = new DefaultHttpClient();
				try {
					client.execute(get, mResHandler2);
					Thread.sleep(3000);
				}
				catch (Exception e) {;}
			}
		}
	}

	ResponseHandler<String> mResHandler2 = new ResponseHandler<String>() {

		@Override
		public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
			StringBuilder html = new StringBuilder();
			try {
				BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
				for (;;) {
					String line = br.readLine();
					if (line == null) break;
					html.append(line + '\n');
				}
				br.close();

				DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
				DocumentBuilder builder = factory.newDocumentBuilder();
				InputStream istream = new ByteArrayInputStream(html.toString().getBytes("utf-8"));
				Document doc = builder.parse(istream);
				Element order = doc.getDocumentElement();

				NodeList mainNList = order.getElementsByTagName("item");
				Node mainNode = mainNList.item(i);
				NodeList subNList = mainNode.getChildNodes();
				Node subNode = subNList.item(2);
				if(!subNode.getTextContent().equals("")) {
					i++;
				}
//				subNode = subNList.item(3);
				String msg = subNList.item(3).getTextContent();

				Message message = mAfterDown2.obtainMessage();
				message.obj = msg;
				mAfterDown2.sendMessage(message);
			}
			catch (Exception e) {;}
			return null;
		}
	};
	
	Handler mAfterDown = new Handler() {
		public void handleMessage(Message msg) {
			arData.add(new SamMsg("", (String)msg.obj));
			adapter.notifyDataSetChanged();
		}
	};
	
	Handler mAfterDown2 = new Handler() {
		public void handleMessage(Message msg) {
			arData.add(new SamMsg((String)msg.obj, ""));
			adapter.notifyDataSetChanged();
		}
	};


	public void mOnClick(View v) {
		commend = (EditText)findViewById(R.id.newmsg);
		String text = commend.getText().toString();
		String url = "http://godling2.cafe24.com/chat/index.php/room/cmsg/name/";
		url += id;
		url += "/data/";
		url += text;
		switch(v.getId()) {
		case R.id.send:
			if (text.length() != 0) {
//				arData.add(new SamMsg("", text));
				commend.setText("");
//				adapter.notifyDataSetChanged();
//				ListView list = (ListView)findViewById(R.id.list);
//				list.setSelection(arData.size() - 1);
				DownThread thread = new DownThread(url);
				thread.start();

			}

		}
	}


	class SamMsg {
		private String OtherMsg, MyMsg;

		SamMsg(String otherMsg, String myMsg) {
			OtherMsg = otherMsg;
			MyMsg = myMsg;
		}
	}

	class SamMsgAdapter extends BaseAdapter {

		private Context context;
		private LayoutInflater Inflater;
		private ArrayList<SamMsg> arSrc;
		private int layout;

		SamMsgAdapter(Context context, int layout, 
				ArrayList<SamMsg> arData){
			this.context = context;
			this.Inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.arSrc = arData;
			this.layout = layout;
		}

		@Override
		public int getCount() {
			return arSrc.size();
		}

		@Override
		public String getItem(int position) {
			SamMsg msg = arSrc.get(position);
			if (msg.MyMsg.length() != 0)
				return msg.MyMsg;

			return msg.OtherMsg;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView,
				ViewGroup parent) {
			if (convertView == null) {
				convertView = this.Inflater.inflate(layout, parent, false);
			}

			TextView otherText = (TextView)convertView.findViewById(R.id.othermsg);
			otherText.setText(arSrc.get(position).OtherMsg);
			TextView myText = (TextView)convertView.findViewById(R.id.mymsg);
			myText.setText(arSrc.get(position).MyMsg);

			return convertView;
		}

	}
}
